package cn.wenhe9.web.client;

import cn.wenhe9.model.pojo.Comment;
import cn.wenhe9.model.responseData.ArticleResponseData;
import cn.wenhe9.service.CommentService;
import cn.wenhe9.utils.MyUtils;
import com.vdurmont.emoji.EmojiParser;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author dujinliang
 * 2021/4/22
 */
@Controller
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    private CommentService commentService;
    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);

    /**
     * 发表评论
     * @param request request用来存储数据
     * @param aid 文章id
     * @param text 评论信息
     * @return 返回状态信息
     */
    @PostMapping("/publish")
    @ResponseBody
    public ArticleResponseData publishComment(HttpServletRequest request, @RequestParam Integer aid, @RequestParam String text){
        //去除js脚本
        text = MyUtils.cleanXSS(text);
        text = EmojiParser.parseToAliases(text);

        //获取当前登录用户
        //User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //封装评论信息
        Comment comment = new Comment();
        comment.setArticleId(aid);
        comment.setIp(request.getRemoteAddr());
        comment.setCreated(new Date());
        comment.setAuthor("user");
        comment.setContent(text);

        try {
            commentService.publishComment(comment);
            logger.info("发布评论成功，对应文章id：" + aid);

            return ArticleResponseData.ok();
        }catch (Exception e){
            logger.error("发布评论失败，对应文章id: "+aid +";错误描述: "+e.getMessage());
            return ArticleResponseData.fail();
        }
    }

}
